using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Tools.PublishWizard.Helpers;
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
	internal class TableDataWrapper : IEnumerable
	{
		private IEnumerable script;

		private Table table;

		private bool hasWritableColumns;

		private bool hasUserDefinedType;

		private string columnNames;

		private ScriptingOptions scriptingOptions;

		private string tableName;

		internal bool HasUserDefinedType
		{
			get
			{
				return this.hasUserDefinedType;
			}
		}

		internal bool HasWritableColumns
		{
			get
			{
				return this.hasWritableColumns;
			}
		}

		internal string TableName
		{
			get
			{
				return this.tableName;
			}
		}

		public TableDataWrapper(IEnumerable script, Table table, ScriptingOptions so)
		{
			this.script = script;
			this.table = table;
			this.scriptingOptions = so;
			this.tableName = ScriptTableCommand.GetTableName(this.scriptingOptions, this.table);
			this.hasWritableColumns = false;
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = true;
			foreach (Column column in this.table.Columns)
			{
				if (column.DataType.SqlDataType != SqlDataType.Timestamp && !column.Computed)
				{
					if (!flag)
					{
						stringBuilder.Append(", ");
					}
					flag = false;
					if (column.DataType.SqlDataType == SqlDataType.UserDefinedType)
					{
						this.hasUserDefinedType = true;
					}
					stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, "[{0}]", new object[]
					{
						column.Name
					}));
				}
			}
			this.hasWritableColumns = (stringBuilder.Length > 0);
			if (this.hasWritableColumns)
			{
				this.columnNames = stringBuilder.ToString();
			}
		}

		internal SqlDataAdapter GetDataAdapter()
		{
			if (!this.HasWritableColumns)
			{
				throw new InvalidOperationException();
			}
			SqlConnection sqlConnection = Connection.ConnectionInstance.SqlConnection;
			return new SqlDataAdapter(string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}", new object[]
			{
				this.columnNames,
				this.tableName
			}), sqlConnection);
		}

		public IEnumerator GetEnumerator()
		{
			return this.script.GetEnumerator();
		}
	}
}
